<template>
<div>
  <h1>欢迎登录</h1>
  <van-cell-group inset>
    <van-field
        v-model="phone"
        required
        left-icon="phone-o"
        label="手机号"
        placeholder="请输入手机号"
    />
    <van-field
        v-model="code"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button size="small" type="primary" :disabled="btn1" @click="sendCode()">{{btnmsg}}</van-button>
      </template>
    </van-field>
    <van-button type="primary" @click="login()" block>登录</van-button>
    未注册手机登录时会自动创建新账号，我已阅读并同意服务协议和隐私权条款
  </van-cell-group>

</div>
</template>

<script>
import { Toast } from 'vant';

export default {
  name: "Login",
  data(){
    return{
      phone: "",
      code:"",
      btnmsg:"发送验证码",
      seconds:60,
      btn1:false
    }
  },methods:{
    sendCode(){
      //开启倒计时
      this.btn1=true;//按钮不可用
      this.btnmsg="重新发送 "+this.seconds+" s";
      //开启定时任务
      var v=setInterval(()=>{
        if(this.seconds>0){
          this.seconds--;
          this.btnmsg="重新发送 "+this.seconds+" s";
        }else {
          clearInterval(v);//停止倒计时
          this.btn1=false;
          this.seconds=60;
          this.btnmsg="再次发送验证码";
        }
      },1000);
      //axios 发送
      this.axios.get("/api/sms/sendlogin.do?phone="+this.phone).
      then(res=>{
        if(res.data.code==200){
            //成功
            Toast("亲，发送成功！");

          }else{
            //失败
            Toast(res.data.msg);
          }
      })
    },
    login(){
      this.axios.get("/api/user/login.do?phone="+this.phone+"&code="+this.code).then(res=>{
        if(res.data.code==200){
          //成功
          this.$store.commit("setTk",res.data.data);
          //跳转到主页 编程式路由
          this.$router.push("/");
        }else{
          //失败
          Toast(res.data.msg);
        }
      })
    }
  }
}
</script>

<style scoped>

</style>

